<?php
/**
 * @version      BOSSCMS-Free
 * @trademark    BOSSCMS
 * @copyright    Copyright © by BOSSCMS-Free (https://www.bosscms.net/) 保留所有权利
 * @license      https://gitee.com/Greenpeas/BOSSCMS/license/ 和 https://www.bosscms.net/freelicense/
 * @link         https://www.bosscms.net/
 * @author       温州软界网络技术有限公司
**/
defined('IS_OK') or exit('Access Forbidden');

into::basic_class('admin');

class group extends admin
{
	public function init()
	{
		global $G;
		$G['cover'] = $this->cover('group');
		if(!$G['get']['column']){
			$G['body_class'] = 'iframe-content';
			$G['navsub'] = into::load_class('admin','items','content','new')->navsub();
		}
		
		$type = arrExist($G,'get|type');
		$items = arrExist($G,'get|items');
		if(!$type && $res=mysql::select_one('type','items',"id='{$items}'")){
			$type = $res['type'];
		}
		if($type && !preg_match('/^(2|3|4|5)$/',$type)){
			alert('栏目类型错误');
		}
		$where = 1;
		if(is_numeric($G['get']['manager']) && $mid=mysql::select_one('id,level','manager',"id='{$G['get']['manager']}' AND (level>{$G['manager']['level']} OR id='{$G['manager']['id']}')")){
			if($mid['level']==1){
				$where = "FIND_IN_SET(issuer,'{$mid['id']},0') AND {$where}";
			}else{
				$where = "issuer='{$mid['id']}' AND {$where}";
			}
		}
		if($keyword = trim($G['get']['keyword'])){
			if(is_numeric($keyword)){
				$where = "id='{$keyword}' AND {$where}";
			}else if(!$mid && $res=mysql::select_one('id,level','manager',"(alias='{$keyword}' OR username='{$keyword}') AND (level>{$G['manager']['level']} OR id='{$G['manager']['id']}')")){
				if($res['level']==1){
					$where = "FIND_IN_SET(issuer,'{$res['id']},0') AND {$where}";
				}else{
					$where = "issuer='{$res['id']}' AND {$where}";
				}
			}else{
				$where = "name LIKE '%{$keyword}%' AND {$where}";
			}
		}
		$man = mysql::select_all('id,alias,username','manager',"level>{$G['manager']['level']} OR id='{$G['manager']['id']}'");
		foreach($man as $v){
			$G['man'][$v['id']] = $v['alias']?$v['alias']:$v['username'];
		}
		if($G['manager']['level']!=1 && $G['manager']['allow'] && !$G['manager']['allow']['read']){
			if($man){
				$where = "FIND_IN_SET(issuer,'{$G['manager']['id']},".implode(',',arrOption($man,'id','id'))."') AND {$where}";
			}else{
				$where = "issuer='{$G['manager']['id']}' AND {$where}";
			}
		}
		$rows = $G['rows'] = $this->rows(20);
		if($type){
			$data = page::group_pages($items, $type, $rows, null, null, null, 'pages', "*", $where, 'mtime DESC, id DESC');
		}else{
			$data = page::group_all($rows, null, null, null, 'pages', "*", $where, 'mtime DESC, id DESC');
		}
		foreach($data['list'] as $k=>$v){
			if($v['issuer']>0){
				$data['list'][$k]['user'] = $G['man'][$v['issuer']];
			}else{
				$data['list'][$k]['user'] = $G['man'][1];
			}
		}
		$data['id'] = $items;
		$data['keyword'] = $keyword;
		$G['subarr'] = page::items_option(0,false,array(),false,'^(2|3|4|5)$');
		$G['models'] = arrOption(mysql::select_all('id,type','items',"FIND_IN_SET(id,'".implode(',',array_keys($G['subarr']))."')"),'id','type');
		$G['get']['type'] = $type;
		if(isset($G['config']['attrflag'])){
			$G['attrflag'] = json::decode($G['config']['attrflag']);
		}else{
			into::basic_json('attrflag');
		}		
		echo $this->theme('group/group', $data);
	}
	
	public function modify()
	{
		global $G;
		$this->cover('group','M');
		if(isset($G['post']['id'])){
			$error=array();
			foreach($G['post']['id'] as $typeid){
				if(isset($G['post']['sort'.$typeid])){
					list($type,$id) = explode('_',$typeid);
					$table = array_search($type,$G['pass']['type']);
					if(!is_numeric(mysql::update(array('sort'=>$G['post']['sort'.$typeid]),$table,"id='{$id}'"))){
						$error[]=$id;
					}
				}
			}
			if($error){
				alert('ID为'.implode(',',$error).'修改失败');
			}else{
				alert('修改成功', $_SERVER['HTTP_REFERER']);
			}
		}else{
			alert('没有提交信息');
		}
	}
	
	public function edit()
	{
		global $G;
		$G['cover'] = $this->cover('group');
		$data = array();
		$data['items'] = $G['get']['items'];
		$type = $G['get']['type'];
		if($res=mysql::select_one('*','items',"id='{$data['items']}'")){
			if(!$type && $res){
				$type = $res['type'];
			}
		}
		$table = array_search($type,$G['pass']['type']);
		$data['ctime'] = $data['mtime'] = date('Y-m-d H:i:s',TIME);
		if($id = $G['get']['id']){
			$data = mysql::select_one('*',$table,"id='{$id}'");
			if($data){
				if($res = mysql::select_one('*',$table.'_content',"id='{$id}'")){
					$data = $data+$res;
				}
				$data['ctime'] = date('Y-m-d H:i:s',$data['ctime']);
				$data['mtime'] = date('Y-m-d H:i:s',$data['mtime']);
				if($data['top'] && $top=mysql::select_one('etime','top',"model='{$type}' AND parent='{$id}'")){
					if($top['etime']>TIME){
						$G['top'][$top['etime']] = '过期时间 '.date('Y-m-d',$top['etime']);
						$data['top'] = $top['etime'];
					}else{
						$data['top'] = 0;
					}
				}
			}
			$data['recommend'] = $data['recommend']=='1'?array('c'):explode(',',$data['recommend']);
			$G['tag'] = array();
			$tag_list = page::tag($type, $id);
			foreach($tag_list as $v){
				$G['tag'][] = $v['title'];
			}
			$G['tag'] = json::encode($G['tag']);
		}
		$G['top'][0] = '默认排序';
		foreach($G['option']['term'] as $k=>$v){
			if($k<0){
				$G['top'][strtotime('+'.abs($k).'day',TIME)] = '置顶'.$v;
			}else if($k>0){
				$G['top'][strtotime("+{$k} month",TIME)] = '置顶'.$v;
			}else{
				$G['top'][1] = '置顶'.$v;
			}
		}
		$config = load::config();
		$G['transfer'] = isset($config['transfer'][$table])?$config['transfer'][$table]:array();
		$G['page'] = array();
		$tpl = dir::read(load::theme().'/html/'.$table.'_detail');
		foreach($tpl['file'] as $v){
			$G['page'][$v] = $v;
		}
		$G['subarr'] = page::items_option(0,false,array(),false,$G['get']['type']?$type:'^(2|3|4|5)$');
		$G['models'] = arrOption(mysql::select_all('id,type','items',"FIND_IN_SET(id,'".implode(',',array_keys($G['subarr']))."')"),'id','type');
		$G['get']['type'] = $type;
		if(isset($G['config']['attrflag'])){
			$G['attrflag'] = json::decode($G['config']['attrflag']);
		}else{
			into::basic_json('attrflag');
		}
		echo $this->theme('group/edit', $data);
	}
	
	/* b o s s c m s */
	public function add()
	{	
		global $G;
		$this->cover('group',arrExist($G['get'],'id')?'M':'A');
		if(isset($G['post'])){
			$subcon = strSub(addslashes(strip_tags(delFilter($G['post']['content']))),0,100);
			$data = array(
				'name'        => $G['post']['name'],
				'items'       => $G['post']['items'],
				'sort'        => $G['post']['sort'],
				'notice'      => $G['post']['notice'],
				'recommend'   => $G['post']['recommend']?implode(',',$G['post']['recommend']):'',
				'top'         => $G['post']['top']>0?1:0,
				'display'     => $G['post']['display'],
				'static'      => arrExist($G['post'],'static'),
				'link'        => $G['post']['recommend']&&in_array('j',$G['post']['recommend'])?$G['post']['link']:'',
				'ctime'       => $G['post']['ctime']?strtotime($G['post']['ctime']):TIME,
				'mtime'       => $G['post']['mtime']?strtotime($G['post']['mtime']):TIME
			);
			$dcon = array(
				'theme'       => $G['post']['theme'],
				'title'       => $G['post']['title'],
				'keywords'    => $G['post']['keywords'],
				'description' => $G['post']['description']?$G['post']['description']:$subcon,
				'alt'         => $G['post']['alt'],
				'target'      => $G['post']['target'],
				'author'      => $G['post']['author']
			);
			if(!($type = arrExist($G['get'],'type'))){
				alert('没有指定栏目类型');
			}
			$table = array_search($type,$G['pass']['type']);
			if(preg_match('/^(2|3|4|5)$/',$type)){
				$dcon['text']      = $G['post']['text']?$G['post']['text']:$subcon;
				$dcon['content']   = $G['post']['content'];
				$dcon['container'] = arrExist($G['post'],'container');
				if(!$dcon['image'] = arrExist($G['post'],'image')){
					preg_match('/<img src="([^"]+)"/',delFilter($dcon['content']),$match);
					if(isset($match[1])){
						$dcon['image'] = addslashes($match[1]);
					}
				}
			}
			if(preg_match('/^(2|3|4)$/',$type)){
				$dcon['text1']    = arrExist($G['post'],'text1');
				$dcon['text2']    = arrExist($G['post'],'text2');
				$dcon['text3']    = arrExist($G['post'],'text3');
				$dcon['image1']   = arrExist($G['post'],'image1');
				$dcon['image2']   = arrExist($G['post'],'image2');
				$dcon['image3']   = arrExist($G['post'],'image3');
				$dcon['images']   = arrExist($G['post'],'images');
			}
			if($type == 3){
				$dcon['icon'] = arrExist($G['post'],'icon');
				$dcon['video'] = arrExist($G['post'],'video');
				$dcon['content1'] = arrExist($G['post'],'content1');
				$dcon['content2'] = arrExist($G['post'],'content2');
				$dcon['content3'] = arrExist($G['post'],'content3');
				$dcon['content4'] = arrExist($G['post'],'content4');
				$dcon['price'] = arrExist($G['post'],'price');
			}else if($type == 5){
				$bosscms_ = true;
				$dcon['file'] = $G['post']['file'];
				$dcon['down'] = $G['post']['down'];
				$dcon['size'] = $G['post']['size'];
				$dcon['icon'] = arrExist($G['post'],'icon');
				if($dcon['file'] && !$dcon['size']){
					$file = url::upload($dcon['file'],'sub',ROOT_PATH);
					$dcon['size'] = is_file($file)?@filesize($file):0;
				}
			}			
			$items = arrExist($G['get'],'items');
			if($items && mysql::total('items',"id='{$items}'")){
				if($id = arrExist($G['get'],'id')){
					if($result = mysql::select_one('id,mtime',$table,"id='{$id}'")){
						if($result['mtime'] == $data['mtime']){
							$data['mtime'] = TIME;
						}
						if(mysql::update($data,$table,"id='{$id}'")){
							if($G['post']['top']>1){
								mysql::select_set(array('model'=>$type,'parent'=>$id,'etime'=>$G['post']['top']),'top',array('etime'));
							}else{
								mysql::delete('top',"model='{$type}' AND parent='{$id}'");
							}
						}
						if(mysql::total($table.'_content',"id='{$id}'")){
							mysql::update($dcon,$table.'_content',"id='{$id}'");
						}else{
							$dcon['id'] = $id;
							mysql::insert($dcon,$table.'_content');
						}
					}else{
						alert('没有内容');
					}
				}else{
					$data['issuer'] = $G['manager']['id'];
					if(!$dcon['author']){
						$dcon['author'] = $G['manager']['alias']?$G['manager']['alias']:$G['manager']['username'];
					}
					if($id = mysql::insert($data,$table)){
						$dcon['id'] = $id;
						mysql::insert($dcon,$table.'_content');
						if($G['post']['top']>1){
							mysql::insert(array('model'=>$type,'parent'=>$id,'etime'=>$G['post']['top']),'top');
						}else{
							mysql::delete('top',"model='{$type}' AND parent='{$id}'");
						}
					}
					$this->sitemap();
				}
				$tag_list = page::tag($type, $id);
				if($tag = arrExist($G['post'],'tag')){
					$tag = json::defilter($tag);
					foreach($tag as $t){
						if($res = mysql::select_one('*','tag',"type='{$type}' AND title='{$t}'")){
							if(strstr(",{$res['parent']},",",{$id},")){
								foreach($tag_list as $i=>$l){
									if($l['title']==stripslashes($t)){
										unset($tag_list[$i]);
									}
								}
							}else{
								mysql::update(array('parent'=>($res['parent']?$res['parent'].',':'').$id),'tag',"id='{$res['id']}'");
							}
						}else{
							mysql::insert(array('type'=>$type,'title'=>$t,'parent'=>$id,'name'=>'','seo_title'=>'','keywords'=>'','description'=>''),'tag');
						}
					}
				}
				foreach($tag_list as $l){
					mysql::update(array('parent'=>preg_replace("/^{$id}$|^{$id},|,{$id},|,{$id}$/i",'',$l['parent'])),'tag',"id='{$l['id']}'");
				}
				$tags = mysql::select_all('id,parent','tag',"type='{$type}' AND FIND_IN_SET('{$id}',parent)");
				foreach($tags as $v){
					mysql::update(array('amount'=>arrExist(mysql::select_one("COUNT(*) AS amount",$table,"FIND_IN_SET(id,'{$v['parent']}') AND display=1"),'amount')),'tag',"id='{$v['id']}'");
				}
				if($type!=2 && isset($G['post']['tc'])){
					value::set($G['post']['tc'], $id, $type);
				}
				alert('操作成功', url::mpf('group','group','edit',array('id'=>$id,'success'=>'ok')));
			}else{
				alert('没有指定栏目');
			}
		}else{
			alert('没有提交信息');
		}
	}
	
	public function attr()
	{
		global $G;
		$id = $G['get']['id'];
		$type = $G['get']['type'];
		$flag = $G['get']['flag'];
		$top = $G['get']['top'];
		if(is_numeric($id) && ($flag || $top) && $table=array_search($type,$G['pass']['type'])){
			if($top){
				if(mysql::update(array('top'=>0),$table,"id='{$id}'")){
					mysql::delete('top',"model='{$type}' AND parent='{$id}'");
				}
			}else if($res = mysql::select_one('recommend',$table,"id='{$id}'")){
				if($flag == 'c'){
					$res['recommend'] = str_replace(1,'',$res['recommend']);
				}
				$data = array('recommend'=>trim(str_replace(',,',',',str_replace($flag,'',$res['recommend'])),','));
				if($flag == 'j'){
					$data['link'] = '';
				}
				mysql::update($data,$table,"id='{$id}'");
			}
			alert('修改成功', $_SERVER['HTTP_REFERER']);
		}else{
			alert('没有提交信息');
		}
	}
	
	public function attrs()
	{
		global $G;
		if($G['post']['recommend'] && $arr=explode(',',$G['get']['id'])){
			foreach($arr as $typeid){
				list($type,$id) = explode('_',$typeid);
				$table = array_search($type,$G['pass']['type']);
				if(is_numeric($id) && $res=mysql::select_one('recommend',$table,"id='{$id}'")){
					$res['recommend'] = trim(preg_replace('/0,?/','',$res['recommend']),',');
					foreach($G['post']['recommend'] as $v){
						if($G['post']['operate']){
							if(!strstr($res['recommend'],$v)){
								$res['recommend'] = $res['recommend'].','.$v;
							}
						}else{
							if($v == 'c'){
								$res['recommend'] = str_replace(1,'',$res['recommend']);
							}
							$res['recommend'] = str_replace(',,',',',str_replace($v,'',$res['recommend']));
						}
					}
					mysql::update(array('recommend'=>trim($res['recommend'],',')),$table,"id='{$id}'");
				}
			}
			if($G['post']['operate']){
				alert('修改成功', url::param($_SERVER['HTTP_REFERER'],'success','ok'));
			}else{
				alert('删除成功', url::param($_SERVER['HTTP_REFERER'],'success','ok'));
			}
		}else{
			alert('没有提交信息');
		}
	}
	
	public function paste()
	{
		global $G;
		$G['cover'] = $this->cover('group');
		if(preg_match('/^(copys|move)$/',$G['get']['action'])){
			$data['action'] = $G['get']['action'];
			$data['subarr'] = page::items_option(0,false,array(),false,$G['get']['type']?$G['get']['type']:'^(2|3|4|5)$');
			echo $this->theme('group/paste',$data);
		}
	}
	
	public function copys()
	{
		global $G;
		$this->cover('group','A');
		if(isset($G['get']['id'])){
			$copys = $G['post']['copys'];
			if(is_numeric($copys) && $res=mysql::select_one('type','items',"id='{$copys}'")){
				$success = $error = array();
				$arr = explode(',',$G['get']['id']);
				foreach($arr as $typeid){
					list($type,$id) = explode('_',$typeid);
					$table = array_search($type,$G['pass']['type']);
					if(is_numeric($id) && $type==$res['type'] && $data=mysql::select_one('*',$table,"id='{$id}'")){
						unset($data['id']);
						$data['items'] = $copys;
						$data['ctime'] = $data['mtime'] = TIME;
						$data['notice'] = 0;
						$data['static'] = '';
						if($nid=mysql::insert($data,$table)){
							if($con=mysql::select_one('*',$table.'_content',"id='{$id}'")){
								$con['id']=$nid;
								mysql::insert($con,$table.'_content');
							}
							$theme = mysql::select_all('*','theme',"extent='{$type}' AND parent='{$id}'");
							foreach($theme as $val){
								unset($val['id']);
								$val['parent'] = $nid;
								mysql::insert($val,"theme");
							}
							$success[] = $id;
						}else{
							$error[] = $id;
						}
					}else{
						$error[] = $id;
					}
				}
				if(!$error && $success){
					$this->sitemap();
					alert('复制成功', url::mpf('group','group','paste',array('action'=>'copys','success'=>'ok')));
				}else if($error && !$success){
					alert('复制失败');
				}else if($success){
					alert('复制成功'.count($success).'个，失败'.count($error).'个', url::mpf('group','group','paste',array('action'=>'copys','success'=>'ok')));
				}
			}else{
				alert('没有指定栏目');
			}		
		}
		alert('没有提交信息');
	}
	
	public function move()
	{
		global $G;	
		$this->cover('group','M');
		if(isset($G['get']['id'])){
			$move = $G['post']['move'];
			if(is_numeric($move) && $res=mysql::select_one('type','items',"id='{$move}'")){
				$success = $error = array();
				$arr = explode(',',$G['get']['id']);
				foreach($arr as $typeid){
					list($type,$id) = explode('_',$typeid);
					$table = array_search($type,$G['pass']['type']);
					if(is_numeric($id) && $type==$res['type'] && mysql::total($table,"id='{$id}' AND items!='{$move}'")){
						if(mysql::update(array('items'=>$move),$table,"id='{$id}'")){
							$success[] = $id;
						}else{
							$error[] = $id;
						}
					}else{
						$error[] = $id;
					}
				}
				if(!$error && $success){
					$this->sitemap();
					alert('移动成功', url::mpf('group','group','paste',array('action'=>'move','success'=>'ok')));
				}else if($error && !$success){
					alert('移动失败');
				}else if($success){
					alert('移动成功'.count($success).'个，失败'.count($error).'个', url::mpf('group','group','paste',array('action'=>'move','success'=>'ok')));
				}
			}else{
				alert('没有指定栏目');
			}
		}
		alert('没有提交信息');
	}
	
	public function delete()
	{
		global $G;	
		$this->cover('group','D');
		if(isset($G['post']['url']) && isset($G['get']['id'])){
			$success = $error = array();
			$arr = explode(',',$G['get']['id']);
			foreach($arr as $typeid){
				list($type,$id) = explode('_',$typeid);
				$table = array_search($type,$G['pass']['type']);
				if(is_numeric($id) && mysql::total($table,"id='{$id}'")){
					if(is_numeric(mysql::delete($table,"id='{$id}'"))){
						mysql::delete($table.'_content',"id='{$id}'");
						mysql::delete('top',"model='{$type}' AND parent='{$id}'");
						mysql::delete('tag',"type='{$type}' AND parent='{$id}'");
						if($res = mysql::select_all('id,parent','tag',"type='{$type}' AND FIND_IN_SET('{$id}',parent)")){
							foreach($res as $v){
								mysql::update(array('parent'=>trim(str_replace(",{$id},",',',",{$v['parent']},"),',')),'tag',"id='{$v['id']}'");
							}
						}
					}else{
						$error[] = $id;
					}
				}else{
					$error[] = $id;
				}
			}
			if($error){
				alert('ID为'.implode(',',$error).'删除失败');
			}else{
				$this->sitemap();
				alert('删除成功', $_SERVER['HTTP_REFERER']);
			}	
		}
		alert('没有提交信息');
	}
}
?>